<template>
  <div>
    <BasicTable @register="registerTable" @fetch-success="onFetchSuccess">
      <template #action="{ record }">
        <TableAction
            :actions="[
                              {
                icon: 'clarity:refresh-line',
                tooltip: '刷新菜单信息',
                onClick: handleRefresh,
              },
              {
                icon: 'clarity:note-edit-line',
                onClick: handleEdit.bind(null, record),
                ifShow: () => hasPermission(['menu_update']),
              },
            ]"
        />
      </template>
    </BasicTable>
    <MenuDrawer @register="registerDrawer" @success="handleSuccess" />
  </div>
</template>
<script lang="ts">
import {defineComponent, nextTick} from 'vue';

import {BasicTable, useTable, TableAction} from '/@/components/Table';
import {getMenuList} from '/@/api/system/menu';

import {useDrawer} from '/@/components/Drawer';
import MenuDrawer from './MenuDrawer.vue';
import {usePermission} from '/@/hooks/web/usePermission';
import {columns, searchFormSchema} from './menu.data';

export default defineComponent({
  name: 'MenuManagement',
  components: {BasicTable, MenuDrawer, TableAction},
  setup() {
    const {hasPermission} = usePermission();
    const [registerDrawer, {openDrawer}] = useDrawer();
    const [registerTable, {reload, expandAll, setLoading}] = useTable({
      title: '菜单列表',
      api: getMenuList,
      columns,
      formConfig: {
        labelWidth: 120,
        schemas: searchFormSchema,
      },
      isTreeTable: true,
      pagination: false,
      striped: false,
      useSearchForm: true,
      showTableSetting: true,
      bordered: true,
      showIndexColumn: false,
      canResize: false,
      actionColumn: {
        width: 80,
        title: '操作',
        dataIndex: 'action',
        slots: {customRender: 'action'},
        fixed: undefined,
      },
    });

    function handleRefresh() {
      setLoading(true)
      setTimeout(() => {
        setLoading(false)
      }, 1000)
    }

    function handleCreate() {
      openDrawer(true, {
        isUpdate: false,
      });
    }

    function handleEdit(record: Recordable) {
      openDrawer(true, {
        record,
        isUpdate: true,
      });
    }

    function handleDelete(record: Recordable) {
      console.log(record);
    }

    function handleSuccess() {
      reload();
    }

    function onFetchSuccess() {
      // 演示默认展开所有表项
      nextTick(expandAll);
    }

    return {
      hasPermission,
      registerTable,
      registerDrawer,
      handleRefresh,
      handleCreate,
      handleEdit,
      handleDelete,
      handleSuccess,
      onFetchSuccess,
    };
  },
});
</script>
